import * as vscode from "vscode";
import { exec } from "child_process";
import { readFileSync } from "fs";
import { getConfig } from "./config";

const run = (command: string) =>
    new Promise<string>((resolve, reject) => {
        exec(command, (error, stdout, stderr) => {
            if (error) {
                reject(`${error.message}`);
                return;
            }
            if (stderr) {
                reject(`${stderr}`);
                return;
            }
            resolve(stdout);
        });
    });

const escape = (...content: string[]) =>
    content.map((c, _, __) => `"${c.replaceAll('"', '\\"').replaceAll('`', '\\`')}"`);

const runPython = (script: string, ...args: string[]) =>
    run(
        `PYTHONWARNINGS="ignore" ${getConfig("python_path")} -c ${escape(script)[0]
        } ${escape(...args).join(" ")}`
    )
        .then(
            (result) => result,
            (err) => {
                throw new Error(err);
            }
        )
        .catch((err) => {
            throw new Error(err);
        });

export const runPythonResource = (
    context: vscode.ExtensionContext,
    fileName: string,
    ...args: string[]
) =>
    runPython(
        readFileSync(context.asAbsolutePath(`resources/${fileName}`)).toString(),
        ...args
    );
